<?php

/**
 *    收银台控制器，其扮演的是收银员的角色，你只需要将你的订单交给收银员，收银员按订单来收银，她专注于这个过程
 *
 *    @author    Garbin
 */
class CashierApp extends ShoppingbaseApp
{
	/**
     *    根据提供的订单信息进行支付
     *
     *    @author    Garbin
     *    @param    none
     *    @return    void
     */
	function index()
	{
		/* 外部提供订单号 */
		$order_id = $_GET['order_id'];

		$order_ids = $this->_get_order_ids($order_id);
		/* 内部根据订单号收银,获取收多少钱，使用哪个支付接口 */
		$order_model =& m('order');

		$order_info = $order_model->find(array(
		'conditions'    => "order_alias.order_id in ({$order_ids}) AND order_alias.buyer_name= '".$this->visitor->get('user_name')."'",
		'fields'        => 'this.order_id,this.order_sn,this.seller_id,this.seller_name,this.buyer_id,this.buyer_name,this.status,this.order_amount,orderextm.consignee,orderextm.region_name,orderextm.address,orderextm.zipcode,orderextm.phone_tel,orderextm.phone_mob,orderextm.shipping_fee',
		'join'          => 'has_orderextm',
		));

		//print_r($order_info);die();
		if (empty($order_info))
		{
			$this->show_warning('no_such_order','查看消费记录',SITE_URL.'/index.php?app=buyer_order&type=allorder');

			exit;
		}

		//print_r($order_info);die();
		/* 订单有效性判断 */
		foreach ($order_info as $id => $order)
		{

			if ($order['status'] == ORDER_CANCELED)
			{
				$this->show_warning('订单'.$order['order_sn'].'已取消','查看消费记录',SITE_URL.'/index.php?app=buyer_order&type=allorder');
				exit;
			}
			else if ($order['status'] != ORDER_PENDING)
			{
				$this->show_warning('订单'.$order['order_sn'].'不是等待付款状态','查看消费记录',SITE_URL.'/index.php?app=buyer_order&type=allorder');
				exit;
			}
		}
		foreach ($order_info as $id => $order)
		{
			$total += $order['order_amount'];
			$consignee['consignee'] = $order['consignee'];
			$consignee['region_name'] = $order['region_name'];
			$consignee['address'] = $order['address'];
			$consignee['zipcode'] = $order['zipcode'];
			$consignee['phone_tel'] = $order['phone_tel'];
			$consignee['phone_mob'] = $order['phone_mob'];
		}

		$order_num = count($order_info);//订单笔数
		//可用余额
		$model_usermoney =& m('usermoney');
		$user_id = intval($this->visitor->get('user_id'));
		$usermoney_info  = $model_usermoney->get_info_by_user_id($user_id);
		$user_money  = $usermoney_info['user_money'];

		if($user_money > 0)
		{

			$mode_usersatety =& m('usersafety');
			$satety_info = $mode_usersatety->get(array(
			'fields' => "pay_password",
			'conditions' => "user_id={$user_id}",
			));
		}

		$is_pay_password = empty($satety_info['pay_password'])?0:1;

		//显示位置
		$shopcar_step = 'shopcar03';
		$this->assign('shopcar_step', $shopcar_step);

		$this->assign('order_info', $order_info);//订单信息
		$this->assign('order_num', $order_num);////订单笔数
		$this->assign('order_ids', $order_ids);////订单笔数
		$this->assign('total', $total);//订单总额
		$this->assign('consignee', $consignee);//收货地址

		$this->assign('user_money', $user_money);  //用户可用余额
		$this->assign('is_pay_password', $is_pay_password);//用户安全密码


		$this->_curlocal(
		LANG::get('cashier')
		);
		$this->_config_seo('title', '选择支付方式' . ' - ' . Conf::get('site_title'));
		$this->display('cashier.payment.html');

	}

	/**
     *    确认支付
     *
     *    @author    Garbin
     *    @return    void
     */
	function goto_pay()
	{
		//订单ID
		//print_r($_POST);die();
		$order_id = $_POST['order_id'];
		$to_online_pay  = intval($_POST['to_online_pay']);//是否线上支付方式
		$pay_type       = intval($_POST['pay_type']);//支付方式
		$self_btn       = intval($_POST['self_btn']);//是否选中余额
		$pay_bank       = addslashes(html_script($_POST['pay_bank']));//支付银行

		$order_ids = $this->_get_order_ids($order_id);

		if (empty($pay_type))
		{
			$this->show_warning('no_such_payment');

			exit;
		}
		if($pay_type == 1)
		$payment_code = 'alipay_bank';//支付宝网上银行
		if($pay_type == 2) //支付宝、财付通或翼支付
		{
			$payment_code = $pay_bank;//支付宝
		}

		//取得订单信息
		$order_model =& m('order');
		$order_info  = $order_model->find(array(
		'conditions'    => "order_id in ({$order_ids}) AND buyer_name= '".$this->visitor->get('user_name')."'",
		'fields'        => 'this.order_id,this.order_sn,this.seller_id,this.seller_name,this.buyer_id,this.buyer_name,this.status,this.order_amount',
		));

		//print_r($order_info);die();
		if (empty($order_info))
		{
			$this->show_warning('no_such_order','查看消费记录',SITE_URL.'/index.php?app=buyer_order&type=allorder');

			return;
		}

		/* 订单有效性判断 */
		foreach ($order_info as $order_id => $order)
		{
			if ($order['status'] == ORDER_CANCELED)
			{
				$this->show_warning('订单'.$order['order_sn'].'已取消','查看消费记录',SITE_URL.'/index.php?app=buyer_order&type=allorder');
				exit;
			}
			else if ($order['status'] != ORDER_PENDING)
			{
				$this->show_warning('订单'.$order['order_sn'].'不是等待付款状态','查看消费记录',SITE_URL.'/index.php?app=buyer_order&type=allorder');
				exit;
			}
		}

		foreach ($order_info as $order_id => $order)
		{
			$total_price += $order['order_amount'];//支付总金额
		}

		if($to_online_pay==0 && $self_btn==1)//支付方式只有余额支付
		{

			$this->_user_money($total_price,1,$order_info);

		}
		else if($to_online_pay==1 && $self_btn==1)//支付方式余额支付和在线支付
		{

			$user_money = $this->_user_money($total_price,0);

		}
		else
		{
			$user_money = 0;
		}

		$online_price = $total_price - $user_money;//在线支付金额
		$online_price = round($online_price,2);

		$out_trade_sn  = $this->_genOrderCode();//外部交易号
		//入库处理,一个外部交易号有可能包含多个订单
		$model_orderpay =& m('orderpay');
		foreach ($order_info as $order_id => $order)
		{

			$insert_data = array(
			'out_trade_sn'  =>  $out_trade_sn,//外部交易号
			'user_id'       =>  intval($this->visitor->get('user_id')),//用户ID
			'order_id'      =>  $order['order_id'],//订单ID
			'payment_code'  =>  $payment_code,//支付方式
			'add_time'      =>  time(),//入库时间
			'total_price'   =>  $total_price,//总金额
			'balance_price' =>  $user_money,//订单中余额支付的总金额
			'order_price'   =>  $order['order_amount'],//订单金额
			);

			$model_orderpay->add($insert_data);

		}

		//$order_model->edit("order_id in ({$order_ids})", $edit_data);//编辑订单的支付信息
		//调用支付网关
		include_once(ROOT_PATH."/includes/payments/{$payment_code}.php");

		$pay = new $payment_code();

		$order_pay['pay_bank']      = $pay_bank; //支付银行
		$order_pay['trans_code']    = $out_trade_sn;//外部交易号
		$order_pay['order_trans_seq']    = $this->_genOrderCode();//订单请求交易流水号  翼支付使用
		$order_pay['trans_amount']  = $online_price;//在线支付订单总额
		$order_pay['body']          = 'order for goods';//商品描述
		$order_pay['buyer_name']    = $order_info['buyer_name'];//客户登录名   翼支付使用
		$order_pay['notify_url']    =  SITE_URL . "/index.php?app=paynotify&act=async&code={$payment_code}";//异步通知接口
		$order_pay['return_url']    =  SITE_URL . "/index.php?app=paynotify&code={$payment_code}";//同步通知接口

		$form_html = $pay->get_code($order_pay);
                $this->_goto_pay($order_pay, $form_html);

	}
        
        public function weixin_png()
        {
            require ROOT_PATH . '/includes/payments/weixin/lib/phpqrcode.php';
            $url = urldecode($_GET["data"]);
            return QRcode::png($url);
        }
        
        private function _goto_pay($order_pay, $result)
        {
            if(!is_array($result)){
                echo $result;
                exit;
            }else{
                $this->assign('order_pay', $order_pay);
                $this->assign('code_url', urlencode($result['code_url']));
                $this->display("cashier.weixin.html");
            }
        }
        
        //余额支付
	function _user_money($total_price,$is_all,$order_info='')
	{


		$ret = $this->_check_pay_password();

		if($ret != 1)
		{
			$this->show_warning('支付密码不对！');

			exit;
		}

		$user_id = intval($this->visitor->get('user_id'));
		$model_usermoney =& m('usermoney');
		$usermoney_info  = $model_usermoney->get_info_by_user_id($user_id);
		$user_money  = $usermoney_info['user_money'];

		if($is_all == 1)//支付方式只有金额支付
		{
			if($user_money < $total_price)
			{
				$this->show_warning('用户余额不足');
				exit;
			}

			$money_arr['user_money']   = $usermoney_info['user_money'] - $total_price; //减少可用金额
			$model_usermoney->edit("user_id = {$user_id}",$money_arr);
			$trans_code = $this->_genOrderCode();
			$accout_log = array(
			'user_id' => $user_id,
			'order_no' => $trans_code,//关联交易号,
			'user_money' => $total_price,
			'change_time' => gmtime(),
			'change_desc' => '礼品卡支付订单',
			'change_type' =>2,
			);

			$model_accountlog =& m('accountlog');//添加到账户充值记录
			$model_accountlog->add($accout_log);

			$notify_result['target'] = ORDER_ACCEPTED;//更新订单状态为买家已付款，等待卖家发货
			if(is_array($order_info))
			{

				$order_type  =& ot('normal');
				foreach ($order_info as $id => $order)
				{
					//改变订单状态
					$notify_result['payment_code'] = 'account';//支付类型
					$notify_result['out_trade_sn'] = $trans_code;//外部交易号
					$notify_result['payment_rate'] = 0;//费率
					$notify_result['pay_amount']   = 0;//手续费

					/* 将验证结果传递给订单类型处理 */
					$order_type->respond_notify($order['order_id'], $notify_result);
				}

			}

			//显示位置
			header('Location:index.php?app=paynotify&act=capital&price='.$total_price);
			exit;

		}
		elseif($is_all == 0)//支付方式有金额支付+在线支付
		{

			if($user_money < 0)
			{
				$this->show_warning('用户余额不足！');
				return;
			}
			$money_arr['user_money']     = $usermoney_info['user_money']   - $user_money; //减少可用金额,余额全部支付完毕,把可用换到冻结
			$money_arr['frozen_money']   = $usermoney_info['frozen_money'] + $user_money ;//冻结金额
			$model_usermoney->edit("user_id = {$user_id}",$money_arr);

			return $user_money;
		}

	}

	function ajaxcheckpaypwd()
	{
		$ret = $this->_check_pay_password();

		if($ret == 1)
		{
			echo ecm_json_encode(true);
			die();
		}
		else
		{
			echo ecm_json_encode(false);
			die();
		}
	}

	//过滤订单ID
	function _get_order_ids($order_id)
	{
		if (empty($order_id))
		{
			$this->show_warning('no_such_order');

			return;
		}
		$order_id_arr = explode(',',$order_id);

		if(!empty($order_id_arr))
		{
			foreach ($order_id_arr as $value)
			{
				$order_ids .= intval($value).',';//过滤
			}
		}

		$order_ids = trim($order_ids,',');

		return $order_ids;

	}


	//生成订单号:年月日时分秒+5位随机数字
	function _genOrderCode()
	{
		return date('YmdHis').$this->_genCode(4);
		//return time().$this->genCode();
	}

	//private 生成指定长度的数字随机数
	function _genCode($len=5)
	{
		$rnd = mt_rand(("1".sprintf("%0".($len-1)."d", 0))+0,("1".sprintf("%0".$len."d", 0))-1);
		$var = sprintf("%0".$len."d", $rnd);
		return $var;
	}


	private function _check_pay_password()
	{

		$user_id = intval($this->visitor->get('user_id'));
		$mode_usersatety =& m('usersafety');
		$satety_info = $mode_usersatety->get(array(
		'fields' => "pay_password",
		'conditions' => "user_id={$user_id}",
		));

		$pay_passw = trim($_REQUEST['pay_passw']);
		if(empty($pay_passw))
		{
			return -1; //请输入支付密码
		}
		$pay_passw = md5(md5($pay_passw, true));

		if(!$satety_info['pay_password'])
		{
			return -2;//请先设置支付密码
		}

		if($pay_passw != $satety_info['pay_password'])
		{

			return -3;//支付密码不正确，请重新输入！

		}

		return 1;

	}



}

?>
